#include<stdlib.h>
#include<stdio.h>
#include<math.h>
#include<iostream>

#include "cv.h"
#include "highgui.h"
#include "read_image.h"


unsigned char * read_color_image(const char * filename , int * w , int * h){

	IplImage* pImg; 

    pImg = cvLoadImage(filename, 1);

	if (pImg == 0){
		printf("Cannot open the image %s \n" , filename);
		exit(0);
	}

    int  width = pImg -> width;
    int  height = pImg -> height;

    *w = width;
	*h = height;

    unsigned char * data = (unsigned char *) pImg->imageData;

    unsigned char * color_image_data = new unsigned char[width * height * 3];

    int tt = 0;

 //   for(int i = 0 ; i < widthstep * height * 3; i++){
//		color_image_data[i] = data[k];
//	    k = k + 1;
//	}

	for (int i = 0 ; i< height ; i++){
		for (int j = 0 ; j < width ; j++){
			for (int k = 0; k < 3 ; k++){
			
			color_image_data[tt] = (pImg->imageData + i*pImg->widthStep)[j*pImg->nChannels + k];
			tt = tt +1;
			
			}
	
		
		}
	}
	return color_image_data;
}


unsigned char * read_gray_image(const char * filename , int * w , int * h){

	IplImage* pImg; 

    pImg = cvLoadImage(filename, 0);

	if (pImg == 0){
		printf("Cannot open the image %s \n" , filename);
		exit(0);
	}

    int  width = pImg -> width;
    int  height = pImg -> height;

    *w = width;
	*h = height;

    unsigned char * data = (unsigned char *) pImg->imageData;

    unsigned char * gray_image_data = new unsigned char[width * height];

    int k = 0;

	for (int i = 0 ; i< height ; i++){
		for (int j = 0 ; j < width ; j++){
			gray_image_data[k] = (pImg->imageData + i*pImg->widthStep)[j];
			k = k + 1;
		}
	}

	return gray_image_data;
}
